import {
  Controller,
  OnApplicationBootstrap,
  Post,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileService } from './file.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiTags, ApiOperation, ApiConsumes, ApiBody } from '@nestjs/swagger';
import { existsSync, mkdirSync } from 'fs';
import { join } from 'path';

export const ApiFile =
  (fileName: string = 'file'): MethodDecorator =>
  (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    ApiBody({
      schema: {
        type: 'object',
        properties: {
          [fileName]: {
            type: 'string',
            format: 'binary',
          },
        },
      },
    })(target, propertyKey, descriptor);
  };

@ApiTags('单文件文件上传接口')
@Controller('file')
export class FileController implements OnApplicationBootstrap {
  constructor(private readonly fileService: FileService) {}
  async onApplicationBootstrap() {
    const filePath = join('public', 'uploadPostCover');
    if (!existsSync(filePath)) {
      mkdirSync(filePath);
    }
  }
  @Post('upload')
  @ApiOperation({ summary: '上传文件' })
  @ApiConsumes('multipart/form-data')
  @ApiFile()
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(
    @UploadedFile('file') file: Express.Multer.File,
  ): Promise<any> {
    console.log(file);
    if (!file) return;
    const fileUrl = await this.fileService.uploadFile(file);
    return { url: fileUrl };
  }

  @Post('uploadPostCoverUrl')
  @ApiOperation({ summary: '上传文章封面' })
  @ApiConsumes('multipart/form-data')
  @ApiFile()
  @UseInterceptors(FileInterceptor('file'))
  async uploadPostCoverUrl(
    @UploadedFile('file') file: Express.Multer.File,
  ): Promise<any> {
    if (!file) return;
    const fileUrl = await this.fileService.uploadFile(file);
    return { url: fileUrl };
  }
}
